package com.zijin.service.user.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.zijin.PageQureyDTO;
import com.zijin.config.SecurityUtils;
import com.zijin.constant.ErrorMsgConstant;
import com.zijin.context.BaseContext;
import com.zijin.dto.user.RolePathDto;
import com.zijin.entity.user.Role;
import com.zijin.entity.user.RolePath;
import com.zijin.entity.user.UserRole;
import com.zijin.exception.BaseException;
import com.zijin.mapper.RolePathMapper;
import com.zijin.service.user.IRolePathService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zijin.vo.user.RolePathVo;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author JWei Xu
 * @since 2025-02-03
 */
@Service
public class RolePathServiceImpl extends ServiceImpl<RolePathMapper, RolePath> implements IRolePathService {


    @Override
    public Set<String> allowedRoutes() {
        Long currentId = BaseContext.getCurrentId();
        if(SecurityUtils.isAdmin()){
            return this.list().stream().map(RolePath::getPath).collect(Collectors.toSet());
        }
        return this.getAllowedRoutes(currentId);
    }

    @Override
    public Set<String> getAllowedRoutes(Long userId) {
        if(SecurityUtils.isAdmin(userId)){
            return this.list().stream().map(RolePath::getPath).collect(Collectors.toSet());
        }

        Set<Long> roleIds = Db.lambdaQuery(UserRole.class)
                .eq(UserRole::getUserId, userId)
                .list().stream().map(UserRole::getRoleId).collect(Collectors.toSet());
        if(ObjectUtil.isEmpty(roleIds)){
            throw new BaseException(ErrorMsgConstant.DEFULT_ROLE_NOT_FOUND);
        }
        return this.lambdaQuery().in(RolePath::getRoleId, roleIds).list().stream().map(RolePath::getPath).collect(Collectors.toSet());
    }

    @Override
    public Page<RolePathVo> getPage(PageQureyDTO dto) {
        return baseMapper.getPage(new Page<>(dto.getPageNum(),dto.getPageSize()),dto.getSearch());
    }

    @Override
    public Boolean addOne(RolePathDto rolePathDto) {
        rolePathDto.setId(null);
        if(ObjectUtil.isEmpty(Db.getById(rolePathDto.getRoleId(),Role.class))){
            throw new BaseException(ErrorMsgConstant.DATA_NOT_FOUN);
        };
        return this.save(BeanUtil.copyProperties(rolePathDto,RolePath.class));
    }

    @Override
    public Boolean delOne(Long id) {
        if(ObjectUtil.isEmpty(this.getById(id))){
            throw new BaseException(ErrorMsgConstant.DATA_NOT_FOUN);
        };
        return this.removeById(id);
    }
}
